package com.groupbuying.cheetah.mq;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.groupbuying.cheetah.service.MqManagentService;
import com.groupbuying.cheetah.utils.JsonUtils;
import com.groupbuying.cheetah.utils.apiresult.ApiResult;
import com.groupbuying.cheetah.utils.apiresult.ApiResultCode;
import com.groupbuying.cheetah.utils.redis.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;


/**
 * MQ消息处理类
 * date 2019年9月5日18:20:21
 */
@Component
public class CheetahMessageListener implements MessageListener {

    public static final Logger logger = LoggerFactory.getLogger(CheetahMessageListener.class);

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MqManagentService mqManagentService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        logger.error(new Date() + "MessageListenerImpl Receive message, Topic is:" + message.getTopic()
                + ", MsgId is:" + message.getMsgID()+",tags is:"+message.getTag());
        logger.error("MessageListenerImpl-->consume topic:"+message.getTag()+"，MsgId:"+message.getMsgID()+"-----message:"+new String(message.getBody()));
        if (message.getTopic().equals(CheetahMQConfig.TOPIC)){
            //获取消息重试次数
            int reconsume = message.getReconsumeTimes();
            if (reconsume == 3) {
                // 消息已经重试了3次，告诉服务器稍后在尝试消费
                logger.error("MessageListenerImpl-->consume topic:"+message.getTag()+"，MsgId:"+message.getMsgID()+" is already try 3 times");
                return Action.CommitMessage;
            }
        }
        if (StringUtils.isNotEmpty(message.getTag()) && CheetahMQConfig.ORDER_PAYMENT_INQUIRY_TAG.equals(message.getTag())){
            //cheetah_Financeorder数据同步
            logger.error("MessageListenerImpl-->"+CheetahMQConfig.ORDER_PAYMENT_INQUIRY_TAG);
            try{
                Map body = JsonUtils.jsonToMap(new String(message.getBody()));
                logger.error("MessageListenerImpl-->body:"+body);
                String orderId = (String) body.get("orderId");

                ApiResult result =  mqManagentService.saveOrderFinanceorder(orderId,CheetahMQConfig.ORDER_PAYMENT_INQUIRY_TAG);
                logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" saveOrderFinanceorder result:::"+JsonUtils.objectToJson(result));
                if(ApiResultCode.RECONSUMELATER.code().equals(result.getCode())){
                    logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum ReconsumeLater");
                    return Action.ReconsumeLater;
                }else{
                    logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum commit");
                    return Action.CommitMessage;
                }
            }catch (Exception e){
                logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum fail",e);
            }
        }else if(StringUtils.isNotEmpty(message.getTag()) && CheetahMQConfig.ORDER_PAYMENT_REFUND_TAG.equals(message.getTag())){
            //cheetah_Financeorder退款数据同步
            logger.error("MessageListenerImpl-->"+CheetahMQConfig.ORDER_PAYMENT_REFUND_TAG);
            try{
                Map body = JsonUtils.jsonToMap(new String(message.getBody()));
                logger.error("MessageListenerImpl-->body:"+body);
                String orderId = (String) body.get("orderId");
                ApiResult result =  mqManagentService.saveOrderFinanceorder(orderId,CheetahMQConfig.ORDER_PAYMENT_REFUND_TAG);
                if(ApiResultCode.RECONSUMELATER.code().equals(result.getCode())){
                    logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum ReconsumeLater");
                    return Action.ReconsumeLater;
                }else{
                    logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum commit");
                    return Action.CommitMessage;
                }
            }catch (Exception e){
                logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+"consum fail",e);
            }
        }else if(StringUtils.isNotEmpty(message.getTag()) && CheetahMQConfig.ORDER_STORE_MONEY_FLOW_TAG.equals(message.getTag())){
            //cheetah_storeMoneyFlow数据同步
            logger.error("MessageListenerImpl-->"+CheetahMQConfig.ORDER_STORE_MONEY_FLOW_TAG);
            try{
                Map body = JsonUtils.jsonToMap(new String(message.getBody()));
                logger.error("MessageListenerImpl-->body:"+body);
                String orderId = (String) body.get("orderId");

                ApiResult result =  mqManagentService.saveOrderStoremoneyflow(orderId);
                if(ApiResultCode.RECONSUMELATER.code().equals(result.getCode())){
                    logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum ReconsumeLater");
                    return Action.ReconsumeLater;
                }else{
                    logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum commit");
                    return Action.CommitMessage;
                }
            }catch (Exception e){
                logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+"consum fail",e);
            }

            return Action.CommitMessage;
        }else if(StringUtils.isNotEmpty(message.getTag()) && CheetahMQConfig.TMP_ORDER_PAY_TAG.equals(message.getTag())){
            //tmp_order_pay数据同步
            logger.error("MessageListenerImpl.tmp_order_pay()-->"+CheetahMQConfig.TMP_ORDER_PAY_TAG);
            try{
                Map body = JsonUtils.jsonToMap(new String(message.getBody()));
                logger.error("MessageListenerImpl.tmp_order_pay()-->body:"+body);
                String orderId = (String) body.get("orderId");

                ApiResult result =  mqManagentService.saveTmpOrderPay(orderId);
                if(ApiResultCode.RECONSUMELATER.code().equals(result.getCode())){
                    logger.error("MessageListenerImpl.tmp_order_pay()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum ReconsumeLater");
                    return Action.ReconsumeLater;
                }else{
                    logger.error("MessageListenerImpl.tmp_order_pay()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum commit");
                    return Action.CommitMessage;
                }
            }catch (Exception e){
                logger.error("MessageListenerImpl.tmp_order_pay()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+"consum fail",e);
            }
            return Action.CommitMessage;
        }else if(StringUtils.isNotEmpty(message.getTag()) && CheetahMQConfig.TMP_ORDER_PAY_REFUND_TAG.equals(message.getTag())){
            //tmp_order_pay退款数据同步
            logger.error("MessageListenerImpl.tmp_order_pay_refund()-->"+CheetahMQConfig.TMP_ORDER_PAY_REFUND_TAG);
            try{
                Map body = JsonUtils.jsonToMap(new String(message.getBody()));
                logger.error("MessageListenerImpl.tmp_order_pay_refund()-->body:"+body);
                String orderId = (String) body.get("orderId");

                ApiResult result =  mqManagentService.saveTmpOrderPayRefund(orderId);
                if(ApiResultCode.RECONSUMELATER.code().equals(result.getCode())){
                    logger.error("MessageListenerImpl.tmp_order_pay_refund()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum ReconsumeLater");
                    return Action.ReconsumeLater;
                }else{
                    logger.error("MessageListenerImpl.tmp_order_pay_refund()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum commit");
                    return Action.CommitMessage;
                }
            }catch (Exception e){
                logger.error("MessageListenerImpl.tmp_order_pay_refund()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+"consum fail",e);
            }
            return Action.CommitMessage;
        }else if(StringUtils.isNotEmpty(message.getTag()) && CheetahMQConfig.TMP_ORDER_SETTLE_TAG.equals(message.getTag())){
            //tmp_order_settle数据同步
            logger.error("MessageListenerImpl.tmp_order_settle()-->"+CheetahMQConfig.TMP_ORDER_SETTLE_TAG);
            try{
                Map body = JsonUtils.jsonToMap(new String(message.getBody()));
                logger.error("MessageListenerImpl.tmp_order_settle()-->body:"+body);
                String orderId = (String) body.get("orderId");
                ApiResult result =  mqManagentService.saveTmpOrderSettle(orderId);
                if(ApiResultCode.RECONSUMELATER.code().equals(result.getCode())){
                    logger.error("MessageListenerImpl.tmp_order_settle()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum ReconsumeLater");
                    return Action.ReconsumeLater;
                }else{
                    logger.error("MessageListenerImpl.tmp_order_settle()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum commit");
                    return Action.CommitMessage;
                }
            }catch (Exception e){
                logger.error("MessageListenerImpl-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+"consum fail",e);
            }

            return Action.CommitMessage;
        }else if(StringUtils.isNotEmpty(message.getTag()) && CheetahMQConfig.TMP_ORDER_SETTLE_REFUND_TAG.equals(message.getTag())){
            //tmp_order_settle退款数据同步
            logger.error("MessageListenerImpl.tmp_order_settle_refund()-->"+CheetahMQConfig.TMP_ORDER_SETTLE_REFUND_TAG);
            try{
                Map body = JsonUtils.jsonToMap(new String(message.getBody()));
                String orderId = (String) body.get("orderId");
                logger.error("MessageListenerImpl.tmp_order_settle_refund()-->body:"+body);
                ApiResult result =  mqManagentService.saveTmpOrderSettleRefund(orderId);
                if(ApiResultCode.RECONSUMELATER.code().equals(result.getCode())){
                    logger.error("MessageListenerImpl.tmp_order_settle_refund()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum ReconsumeLater");
                    return Action.ReconsumeLater;
                }else{
                    logger.error("MessageListenerImpl.tmp_order_settle_refund()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum commit");
                    return Action.CommitMessage;
                }
            }catch (Exception e){
                logger.error("MessageListenerImpl.tmp_order_settle_refund-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+"consum fail",e);
            }

            return Action.CommitMessage;
        }else if(StringUtils.isNotEmpty(message.getTag()) && CheetahMQConfig.TMP_ORDER_FLOW_TAG.equals(message.getTag())){
            //tmp_order_flow数据同步
            logger.error("MessageListenerImpl.tmp_order_flow()-->"+CheetahMQConfig.TMP_ORDER_FLOW_TAG);
            try{
                Map body = JsonUtils.jsonToMap(new String(message.getBody()));
                logger.error("MessageListenerImpl.tmp_order_flow()-->body:"+body);
                String orderId = (String) body.get("orderId");
                ApiResult result =  mqManagentService.saveTmpOrderFlow(orderId);
                if(ApiResultCode.RECONSUMELATER.code().equals(result.getCode())){
                    logger.error("MessageListenerImpl.tmp_order_flow()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum ReconsumeLater");
                    return Action.ReconsumeLater;
                }else{
                    logger.error("MessageListenerImpl.tmp_order_flow()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum commit");
                    return Action.CommitMessage;
                }
            }catch (Exception e){
                logger.error("MessageListenerImpl.tmp_order_flow()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+"consum fail",e);
            }

            return Action.CommitMessage;
        }else if(StringUtils.isNotEmpty(message.getTag()) && CheetahMQConfig.TMP_ORDER_FLOW_REFUND_TAG.equals(message.getTag())){
            //tmp_order_flow退款数据同步
            logger.error("MessageListenerImpl.tmp_order_flow_refund()-->"+CheetahMQConfig.TMP_ORDER_FLOW_TAG);
            try{
                Map body = JsonUtils.jsonToMap(new String(message.getBody()));
                logger.error("MessageListenerImpl.tmp_order_flow_refund()-->body:"+body);
                String orderId = (String) body.get("orderId");
                ApiResult result =  mqManagentService.saveTmpOrderFlowRefund(orderId);
                if(ApiResultCode.RECONSUMELATER.code().equals(result.getCode())){
                    logger.error("MessageListenerImpl.tmp_order_flow_refund()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum ReconsumeLater");
                    return Action.ReconsumeLater;
                }else{
                    logger.error("MessageListenerImpl.tmp_order_flow_refund()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+" consum commit");
                    return Action.CommitMessage;
                }
            }catch (Exception e){
                logger.error("MessageListenerImpl.tmp_order_flow_refund()-->consume tag:"+message.getTag()+"，MsgId:"+message.getMsgID()+"consum fail",e);
            }

            return Action.CommitMessage;
        }
        logger.error("MessageListenerImpl.tmp_order_flow()-->consume topic:"+message.getTag()+"，MsgId:"+message.getMsgID()+"consum fail");
        return Action.CommitMessage;
        //如果想测试消息重投的功能,可以将Action.CommitMessage 替换成Action.ReconsumeLater
    }

}
